package com.leizhi.demo.monitor.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description Token 工具类
 * @Version 1.0.0-SNAPSHOT
 * @Author leizhi
 * @Date 2025/4/29 15:35
 */
public class TokenUtil {

    /* 过期时间 */
    public static final long EXPIRE_DATE = 2 * 60 * 60 * 1000;
    /* 加密秘钥 */
    private static final String TOKEN_SECRET = "ZCaffsUUHugGuru2020BOWER";


    public static String token(String userName, String password) {
        try {
            JWTCreator.Builder builder = builder();
            builder.withClaim("userName", userName);
            builder.withClaim("password", password);
            return builder.sign(Algorithm.HMAC256(TOKEN_SECRET));
        } catch (Exception e) {
            return null;
        }
    }

    public static boolean verify(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    private static JWTCreator.Builder builder() {
        //设置头部信息
        Map<String, Object> header = new HashMap<>();
        header.put("typ", "JWT");
        header.put("alg", "HS256");

        JWTCreator.Builder builder = JWT.create();
        builder.withHeader(header);
        builder.withExpiresAt(new Date(System.currentTimeMillis() + EXPIRE_DATE));
        return builder;
    }

}
